<script setup lang="ts">
	import { ref, reactive, unref, computed } from 'vue'
	import { onLoad, onShow } from '@dcloudio/uni-app'
	import { useNotify } from '@/hooks/web/useNotify/index.js'
	import { orderSettle, orderAdd } from '@/package_saleman/api/Order'
	import { checkStock } from '@/package_saleman/api/Home'
	// 消息弹窗
	const NotifyRef = ref<any>(null)
	const { showNotify } = useNotify(NotifyRef)

	const remark = ref('')

	// 路由参数
	interface RouteParams {
		store_id : string,
		cart_id : string,
		warehouse_id : string,
		warehouse_type : '1' | '2'
	}
	const routeParams = ref<RouteParams>({
		store_id: '',
		cart_id: '',
		warehouse_id: '',
		warehouse_type: '2'
	})
	const receive_money = ref(0)
	onLoad((options) => {
		routeParams.value = options as RouteParams
		receive_money.value = options.amount
		getList(JSON.parse(options.data))
	})
	const receive_type = ref('')
	const useOrderDetail = () => {
		const dataList = ref({})
		const getList = async (option) => {
			// const params = {
			// 	...routeParams.value
			// }
			// const res = await orderSettle(params)
			dataList.value = option;
			dataList.value = [...dataList.value.pt, ...dataList.value.send]
		}

		return {
			dataList,
			getList,
		}
	}
	const { dataList, getList } = useOrderDetail()

	const show = ref(false)
	const pay_type = ref(0)
	const pay_name = ref('请选择')
	const money = ref((0).toFixed(2));
	const columns = reactive([
		[
			{
				label: '现金',
				id: 1
			},
			{
				label: '公司账户',
				id: 2
			},
			{
				label: '挂账',
				id: 3
			}
		]
	]);

	const cancel = () => {
		show.value = false
	}

	const confirm = (e) => {
		money.value = Number(receive_money.value).toFixed(2)
		pay_type.value = e.value[0].id
		pay_name.value = e.value[0].label
		show.value = false
	}
	const useUploadImg = () => {
		const fileList1 = ref<any[]>([])

		// 添加图片
		type UploadImageFile = {
			size : number,
			type : 'image',
			url : string,
			thumb : string
		}
		type UploadImageParams = {
			file : UploadImageFile | UploadImageFile[],
			index : number,
			name : string
		}
		type AddImage = (event : UploadImageParams) => any
		// 新增图片
		const addImage = async (event) => {
			// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file);
			let fileListLen = fileList1.value.length;
			lists.map((item) => {
				fileList1.value.push({
					...item,
					status: 'uploading',
					message: '上传中',
				});
			});
			for (let i = 0; i < lists.length; i++) {
				const result = await uploadImage(lists[i].url);
				let item = fileList1.value[fileListLen];
				fileList1.value.splice(fileListLen, 1, {
					...item,
					status: 'success',
					message: '',
					url: result,
				});
				fileListLen++;
			}
		};

		const uploadImage = (url) => {
			return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
					url: `${process.env.VUE_APP_BASE_URL}/salesman/upload`,
					filePath: url,
					name: 'file',
					header: {
						'content-type': 'application/json;charset=utf-8',
						'token': uni.getStorageSync('trioToken'),
					},
					success: (res) => {
						const data = JSON.parse(res.data)
						if (data.code !== 200) {
							uni.showToast({
								title: `${data.msg},请重新上传!`,
								icon: 'none'
							})
							return
						}
						setTimeout(() => {
							resolve(data.data.url);
						}, 1000);
					},
				});
			});
		};
		// 删除图片
		const delImage = (event : UploadImageParams) => {
			fileList1.value.splice(event.index, 1)
		}

		return {
			fileList1,
			addImage,
			delImage,
			uploadImage
		}
	}

	const { fileList1, addImage, delImage, uploadImage } = useUploadImg()

	const validatePositive = () => {
		// 检查输入是否为有效数字
		if (isNaN(Number(money.value))) {
			showNotify({
				type: 'error',
				message: '请输入有效的数字金额！'
			});
			money.value = (0).toFixed(2); // 重置为 0.00
			return false;
		}
		// 检查金额是否为正数
		if (Number(money.value) < 0) {
			showNotify({
				type: 'error',
				message: '金额必须为正数！'
			});
			money.value = (0).toFixed(2); // 重置为 0.00
			return false;
		}
		// 检查金额是否大于订单金额
		if (Number(money.value) > Number(receive_money.value)) {
			showNotify({
				type: 'error',
				message: '不可以大于订单金额！'
			});
			money.value = receive_money.value.toFixed(2);
			return false;
		}
		// 确保 money 保留两位小数
		money.value = Number(money.value).toFixed(2);
	};

	const submitLoading = ref(false)
	const submit = async () => {
		if (Number(receive_type.value) == 1) {
			if (!pay_type.value) {
				showNotify({
					type: 'error',
					message: '请选择收款方式'
				})
				return false
			}
			// 图片
			if (fileList1.value.length == 0) {
				showNotify({
					type: 'error',
					message: '请上传图片！'
				});
				return false;
			}
		}
		if (!receive_type.value) {
			showNotify({
				type: 'error',
				message: '请选择结算方式'
			})
			return false
		}
		submitLoading.value = true
		try {
			const filteredItems = dataList.value.filter(item => item.num > 0);
			const checkData = filteredItems.map((res) => {
				return {
					id: res.goods_id,
					num: res.num * res.spec.conversion_rate
				}
			})
			const rs = await checkStock({warehouse_id: unref(routeParams).warehouse_id,goods:JSON.stringify(checkData)})
			
			const data1 = filteredItems.map((res) => {
				return {
					id: res.id,
					goods_id: res.goods_id,
					goods_spec_id: res.goods_spec_id,
					unit: res.unit,
					goods_type: res.goods_type,
					sale_price: res.sale_price,
					true_price: res.true_price,
					real_price: res.true_price,
					total_price: res.total_price,
					num: res.num,
					remark: res.remark
				}
			})
			const params = {
				detail: JSON.stringify(unref(data1)),
				store_id: unref(routeParams).store_id,
				remark: remark.value,
				receive_type: receive_type.value,
				order_type: 1,
				type: 2,
				warehouse_id: unref(routeParams).warehouse_id,
				pay_type: pay_type.value,
				money: money.value,
				image: fileList1.value.map((item) => item.url).join(',')
			}
			const res = await orderAdd(params)
			showNotify({
				type: 'success',
				message: res.msg
			})
			setTimeout(() => {
				
				submitLoading.value = false
				uni.redirectTo({
					url: `/package_saleman/pages/Carsales/index`
				})
			}, 500)

		} catch (err) {
			showNotify({
				type: 'error',
				message: err.msg
			})
			submitLoading.value = false
		}
	}
	const autoChange = () => {
		money.value = receive_money.value.toFixed(2)
	}
</script>

<template>
	<view class="content">
		<up-navbar title="结算台" autoBack placeholder></up-navbar>
		<view class="goods-box">
			<view class="box-header" v-if="dataList">商品详情</view>
			<view class="line"></view>
			<view class="main-box" v-for="(item, index) in dataList" :key="index">
				<view class="main-left">
					<up-image :show-loading="true" :src="item.goods?.img" width="140rpx" height="140rpx"></up-image>
					<view class="gift" v-if="item.goods_type == 2">赠品</view>
				</view>
				<view class="main-right">
					<view class="right-header">
						<view class="header-name">{{item.goods?.goods_name}}{{item.spec?.spec_name}}</view>
						<view style="color: rgba(155, 157, 159, 1);">
							￥{{item.true_price}}*{{item.num}}{{item.spec?.unit_name}}</view>
					</view>
					<view class="right-mod">{{item.goods?.code69}}</view>
					<view class="right-foot">
						<view style="color: rgba(106, 107, 107, 1);">修改前：<text
								style="color: rgba(36, 34, 34, 1);">￥{{item.sale_price}}</text></view>
						<view style="color: rgba(55, 131, 252, 1);">修改后：￥{{item.true_price}}
						</view>
						<view style="font-size: 28rpx;color: rgba(245, 99, 81, 1);">￥{{item.total_price}}</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 结算方式 -->
		<view class="payment-method">
			<view class="method-header">
				<view class="header-left">结算方式</view>
			</view>
			<view class="payment-container">
				<up-radio-group v-model="receive_type" placement="column" iconPlacement="right">
					<up-radio :customStyle="{marginBottom: '8px'}" name="1" label="现结"
						:disabled="dataList.is_bill == 2">
					</up-radio>
					<up-radio :customStyle="{marginBottom: '8px'}" name="2" label="账期"
						:disabled="dataList.is_bill == 1">
					</up-radio>
					<up-radio :customStyle="{marginBottom: '8px'}" name="3" label="预存款"
						:disabled="dataList.is_bill == 2">
					</up-radio>
				</up-radio-group>
			</view>
		</view>
		<view v-if="receive_type == 1">
			<!-- 支付方式 -->
			<view class="payment-method">
				<view class="method-header">
					<view class="header-left">收款方式</view>
					<view class="header-right" @click="show = true">{{pay_name}}></view>
				</view>
				<view class="method-line"></view>
				<view class="method-main">
					<view class="main-name">收款金额</view>
				</view>
				<view class="method-foot" v-if="pay_type == 3">
					<up-text mode="price" text="0"></up-text>
				</view>
				<view class="method-foot" v-else>
					<up-input v-model="money" type="number" placeholder="" border="none" prefixIcon="￥"
						prefixIconStyle="font-size: 15px;" @blur="validatePositive()"></up-input>
				</view>
			</view>
			<view class="content-foot">
				<view class="foot-name">图片</view>
				<view class="img-list">
					<up-upload :fileList="fileList1" @afterRead="addImage" @delete="delImage" multiple :maxCount="3"
						:previewFullImage="true"></up-upload>
				</view>
			</view>
		</view>
		<!-- 订单备注 -->
		<view class="payment-method">
			<view class="method-header">
				<view class="header-left">订单备注</view>
			</view>
			<view class="method-foot">
				<up-input placeholder="备注信息" border="surround" v-model="remark"></up-input>
			</view>
		</view>
		<view class="submit-area-placeholder"></view>
		<view class="submit-area">
			<view class="info">
				<view class="line">
					<text class="label">总计：</text>
					<text
						style="color: #F54E4E;font-size: 28rpx;">￥{{dataList?.reduce((cur, item) => cur + Number(item.total_price), 0).toFixed(2)}}</text>
				</view>
			</view>
			<view class="submit-btn">
				<up-button text="提交" shape="circle" :loading="submitLoading" :disabled="submitLoading"
					color="rgba(55, 131, 252, 1)" @click="submit"></up-button>
			</view>
		</view>
		<up-picker :show="show" :columns="columns" keyName="label" @cancel="cancel" @confirm="confirm"
			:closeOnClickOverlay="true"></up-picker>
		<up-notify ref="NotifyRef"></up-notify>
	</view>
</template>

<style scoped lang="scss">
	.content {
		width: 100%;
		min-height: 100vh;
		background: rgba(242, 243, 245, 1);

		.goods-box {
			width: 702rpx;
			border-radius: 13rpx;
			background: rgba(255, 255, 255, 1);
			margin: 20rpx auto;
			padding: 30rpx;
			box-sizing: border-box;

			.box-header {
				font-size: 28rpx;
				font-weight: 700;
				color: rgba(2, 14, 36, 1);
			}

			.line {
				width: 654rpx;
				height: 2rpx;
				background: rgba(0, 0, 0, 0.1);
				margin: 20rpx 0rpx;
			}

			.main-box {
				display: flex;
				margin-top: 40rpx;

				.main-left {
					width: 140rpx;
					height: 140rpx;
					margin-right: 20rpx;
					position: relative;

					.gift {
						position: absolute;
						top: 0;
						left: 0;
						width: 60rpx;
						height: 32rpx;
						border-radius: 6rpx 0rpx 0rpx 0rpx;
						background: rgba(55, 131, 252, 1);
						font-size: 22rpx;
						font-weight: 500;
						color: rgba(255, 255, 255, 1);
						text-align: center;
						line-height: 32rpx;
					}
				}

				.main-right {
					width: 100%;
					font-size: 24rpx;
					font-weight: 500;

					.right-header {
						display: flex;
						justify-content: space-between;

						.header-name {
							font-size: 28rpx;
							color: rgba(2, 14, 36, 1);
						}

					}

					.right-mod {
						color: rgba(106, 107, 107, 1);
						margin: 20rpx 0rpx;
					}




					.right-foot {
						display: flex;
						justify-content: space-between;
					}
				}
			}
		}

		.payment-method {
			width: 702rpx;
			border-radius: 13rpx;
			background: rgba(255, 255, 255, 1);
			margin: 20rpx auto;
			padding: 30rpx;
			box-sizing: border-box;

			.method-header {
				display: flex;
				justify-content: space-between;

				.header-left {
					font-size: 28rpx;
					color: rgba(2, 14, 36, 1);
				}

				.header-right {
					font-size: 24rpx;
					font-weight: 500;
					color: rgba(155, 157, 159, 1);
				}
			}

			.method-line {
				width: 654rpx;
				height: 2rpx;
				background: rgba(0, 0, 0, 0.1);
				margin: 20rpx 0rpx;
			}

			.method-main {
				display: flex;
				justify-content: space-between;

				.main-name {
					font-size: 28rpx;
					color: rgba(2, 14, 36, 1);
				}

			}

			.payment-container {
				display: flex;
				justify-content: space-between;
				margin-top: 40rpx;
			}

			.method-foot {
				margin: 20rpx 0rpx;
			}
		}

		.content-foot {
			width: 702rpx;
			border-radius: 12rpx;
			background: rgba(255, 255, 255, 1);
			padding: 30rpx;
			box-sizing: border-box;
			margin: 20rpx auto;

			.foot-name {
				font-size: 28rpx;
				font-weight: 700;
				color: rgba(2, 14, 36, 1);
			}

			.img-list {
				margin-top: 20rpx;
			}

		}

		.submit-area-placeholder {
			width: 100%;
			height: 100rpx;
			padding-top: 20rpx;
			padding-bottom: constant(safe-area-inset-bottom);
			/* 兼容iOS < 11.2 */
			padding-bottom: env(safe-area-inset-bottom);
			/* 兼容iOS 11.2及以上 */
		}

		.submit-area {
			position: fixed;
			left: 0;
			bottom: 0;
			z-index: 10;
			display: flex;
			align-items: center;
			justify-content: space-between;
			width: calc(100% - 80rpx);
			height: 100rpx;
			background-color: #FFF;
			padding: 0 40rpx;
			padding-bottom: constant(safe-area-inset-bottom);
			/* 兼容iOS < 11.2 */
			padding-bottom: env(safe-area-inset-bottom);
			/* 兼容iOS 11.2及以上 */
			box-shadow: 0rpx -4rpx 8rpx 0rpx #efefef;

			.info {
				flex: 2;
				display: flex;
				flex-direction: column;

				.line {
					display: flex;
					gap: 12rpx;
					color: #9C9AA1;
				}

				.label {
					font-size: 28rpx;
				}
			}

			.submit-btn {
				flex: 1;
			}
		}
	}
</style>